<?php

namespace app\api\controller;

use app\api\model\ConfigSystem as Config;
use app\api\model\YaoqingRecords;
use think\Db;
use think\Validate;
use think\Request;

class Addressgoods extends Common {
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        // exit(json_encode(['code'=>200, 'data'=>[]]));
        // exit(json_encode(['code'=>400, 'msg'=>'该功能已永久关闭']));
    }
    /**
     * @param $id
     * @param $address_id
     * @param $name
     * @param $images
     * @param $description
     * @param $oldprice
     * @param $price
     * @param $stock
     * @param $expire
     * @param $use_time
     * @param $rule
     * @param $state
     * @return mixed
     */
    public function add($id = '', $address_id = '', $name = '', $images = '', $description = '', $oldprice = '', $price = '', $stock = '', $expire = '', $use_time = 0, $rule = '', $state = 1) {
        $timenow = time();
        $rules   = [
            'address_id'  => 'require',
            'name'        => 'require|max:60',
            'images'      => 'require',
            'description' => 'require',
            'price'       => 'require|between:0.01,99999999',
            'stock'       => 'require|between:1,99999999',
            'expire'      => 'require|between:1,99999999',
            'use_time'    => 'require',
            // 'state'       => 'require|in:0,1',
        ];

        $msg = [
            'address_id.require'  => '地址错误',
            'name.require'        => '地址名称必填',
            'name.max'            => '地址名称最多不能超过40个字符',
            'images.require'      => '图片必须上传',
            'description.require' => '商品描述必须填写',
            'price.require'       => '金额必须填写',
            'price.between'       => '金额填写错误',
            'stock.require'       => '库存必须填写',
            'stock.between'       => '库存填写错误',
            'expire.require'      => '有效期必须填写',
            'expire.between'      => '有效期填写错误',
            'use_time.require'    => '可用时间选择错误',
            // 'state.require'       => '上架状态错误',
            // 'state.in'            => '上架状态错误',
        ];
        $data = [
            'address_id'  => $address_id,
            'name'        => $name,
            'images'      => $images,
            'description' => $description,
            'oldprice'    => $oldprice,
            'price'       => $price,
            'stock'       => $stock,
            'expire'      => $expire,
            'use_time'    => $use_time,
            'rule'        => $rule,
            // 'state'       => $state,
            'create_time' => $timenow,
            'update_time' => $timenow,
        ];

        $validate = new Validate($rules, $msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }
        $store = Db::name('user_claim_address')->where(['id' => $address_id, 'user_id' => $this->member['id'], 'state' => 1])->cache(60)->find();
        if (!$store) {
            return $this->miss('无权操作');
        }
        $method      = '添加';
        $status_desc = '';
        $config      = Config::index('check');
        if ($config['check_address_goods']) {
            $data['status'] = 0;
            $status_desc    = ',待审核';
        } else {
            $data['status'] = 1;
        }
        if ($id) {
            unset($data['address_id'], $data['create_time']);
            $method = '修改';
            $res    = Db::name('user_address_goods')->where(['id' => $id])->update($data);
        } else {
            $data['number'] = strtoupper(uniqid('AG'));
            $res            = Db::name('user_address_goods')->insertGetid($data);
            $data['id']     = $res;
        }
        if ($res) {
            return $this->pass($method . '成功' . $status_desc, 'data', $data);
        }
        return $this->miss($method . '失败');
    }

    /**
     * @param $address_id
     * @param $page
     * @param $pagesize
     * @param array $where
     * @param $field
     * @return mixed
     */
    public static function get($address_id, $page = 1, $pagesize = 20, $where = [], $field = '') {
        $where = array_merge(['address_id' => $address_id, 'delete_time' => 0], $where);
        $field = 'id,name,images,oldprice,price,sold' . ($field ? ',' . $field : '');
        $data  = Db::name('user_address_goods')
            ->where($where)
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->field($field)
            ->order('update_time desc')
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['images'] = explode(',', $value['images']);
            $data[$key]['image']  = $data[$key]['images'][0];
            unset($data[$key]['images']);
        }
        return $data;
    }

    /**
     * @param $address_id
     * @param $page
     * @param $pagesize
     */
    public function lists($address_id, $page = 1, $pagesize = 20) {
        $addressInfo = Db::name('user_claim_address')->find($address_id);
        if (!$addressInfo) {
            return $this->miss('地点错误');
        }
        $field = '';
        $where = [];
        if ($addressInfo['user_id'] == $this->member['id']) {
            $field = 'state,status,reason';
        } else {
            $where = ['state' => 1];
        }

        $data = self::get($address_id, $page, $pagesize, $where, $field);
        return $this->pass($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function dele($id) {
        $good = Db::name('user_address_goods')->where(['id' => $id, 'delete_time' => 0])->find();
        if (!$good) {
            return $this->miss('商品不存在');
        }
        $store = Db::name('user_claim_address')->where(['id' => $good['address_id'], 'user_id' => $this->member['id'], 'state' => 1])->cache(60)->find();
        if (!$store) {
            return $this->miss('无权操作');
        }
        $result = Db::name('user_address_goods')->where(['id' => $id])->update(['delete_time' => time()]);
        if ($result) {
            return $this->pass('删除成功');
        }
        return $this->miss('删除失败');
    }

    /**
     * @param $id
     * @param $state
     * @return mixed
     */
    public function setState($id) {
        $good = Db::name('user_address_goods')->where(['id' => $id, 'delete_time' => 0])->find();
        if (!$good) {
            return $this->miss('商品不存在');
        }
        $store = Db::name('user_claim_address')->where(['id' => $good['address_id'], 'user_id' => $this->member['id'], 'state' => 1])->cache(60)->find();
        if (!$store) {
            return $this->miss('无权操作');
        }
        if ($good['status'] != 1) {
            return $this->miss('商品审核通过后才能上架');
        }
        $state = $good['state'] == 1 ? 0 : 1;

        $cachekey = 'AddressGoodsetState' . $id;
        $num      = cache($cachekey);
        if ($num >= 3) {
            return $this->miss('操作频繁');
        }
        $num = $num ? ++$num : 1;
        cache($cachekey, $num, 10);

        $update = ['state' => $state];
        $result = Db::name('user_address_goods')->where(['id' => $id])->update($update);
        if ($result) {
            return $this->pass('操作成功', 'data', $update);
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $id
     * @param $num
     * @param $paymethod
     * @param $h5
     * @return mixed
     */
    public function CreateOrder($id, $num = 1, $paymethod = 2, $coupon_id = 0, $h5 = 0) {
        $goodInfo = Db::name('user_address_goods')->where(['id' => $id, 'state' => 1, 'status' => 1, 'delete_time' => 0])->field('sold,status,reason,state,create_time,update_time,delete_time', 'filter')->find();
        if (!$goodInfo) {
            return $this->miss('商品不存在');
        }
        $store = Db::name('user_claim_address')->where(['id' => $goodInfo['address_id'], 'state' => 1])->cache(60)->find();
        if (!$store) {
            return $this->miss('店铺未找到');
        }
        if ($store['user_id'] == $this->member['id']) {
            return $this->miss('不支持的操作');
        }
        if ($num < 1 || intval($num) != $num) {
            return $this->miss('错误的操作');
        }
        if ($num > $goodInfo['stock']) {
            return $this->miss('库存不足');
        }
        $timenow = time();
        $order   = [
            'user_id'     => $this->member['id'],
            'shopowner'   => $store['user_id'],
            'address_id'  => $store['id'],
            'number'      => uniqid('ag'),
            'good_id'     => $id,
            'name'        => $goodInfo['name'],
            'image'       => explode(',', $goodInfo['images'])[0],
            'price'       => round($goodInfo['price'] * $num, 2),
            'num'         => $num,
            'expire_time' => $timenow + (86400 * $goodInfo['expire']),
            'data'        => json_encode($goodInfo, JSON_UNESCAPED_UNICODE),
            'create_time' => $timenow,
            'update_time' => $timenow,
        ];

        $useCoupon = false;
        if ($coupon_id) {
            $coupon = Db::name('user_coupon')->where(['state' => 0, 'user_id' => $this->member['id'], 'id' => $coupon_id, 'address_id' => $goodInfo['address_id']])->find();
            if ($coupon) {
                if ($coupon['minprice'] < $order['price'] && $coupon['price'] > 0 && $coupon['price'] <= $order['price']) {
                    $order['price']     = $order['price'] - $coupon['price'];
                    $useCoupon          = true;
                    $order['coupon_id'] = $coupon_id;
                }
            }
        }
        $res = false;
        Db::startTrans();
        try {
            if ($useCoupon) {
                Db::name('user_coupon')->where(['id' => $coupon_id])->update(['update_time' => $timenow, 'state' => 1, 'data' => $order['number']]);
            }
            Db::name('user_address_goods')->where(['id' => $id])->setDec('stock', $num);
            $res = Db::name('order_of_addressgood')->insertGetId($order);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if ($res) {
            $result = $this->payment($res, $paymethod, $h5, false);
            return $result ? $this->pass($result) : $this->miss('订单不存在');
        } else {
            return $this->miss('创建订单失败');
        }
    }

    /**
     * @param $order_id
     * @param $paymethod
     * @param $h5
     * @param $returnJson
     * @return mixed
     */
    public function payment($order_id = '', $paymethod = 2, $h5 = 0, $returnJson = true, $w2 = 0) {
        $order = Db::name('order_of_addressgood')->master()->where(['id' => $order_id, 'user_id' => $this->member['id'], 'status' => 0, 'paystate' => 0, 'delete' => ['<>', 1]])->find();
        if (!$order) {
            return $returnJson ? $this->miss('订单不存在') : '订单不存在';
        }
        if ($order['paystate'] != 0 || $order['status'] != 0) {
            return $returnJson ? $this->miss('订单状态错误') : '订单状态错误';
        }

        switch ((int) $paymethod) {
        case 2:
            $action = 'api/Alipay/tradeAppPay';
            break;
        case 3:
            $action = 'api/Wechat/app';
            if ($w2) {
                $action = 'api/Wechat2/app';
            }
            break;
        default:
            return $returnJson ? $this->miss('支付方式错误') : '支付方式错误';
            break;
        }
        Db::name('order_of_addressgood')->where(['id' => $order['id']])->update(['paymethod' => $paymethod]);
        if ($h5) {
            $return = ['order_sn' => $order['number'], 'url' => 'api/wap/pay'];
            return $returnJson ? $this->pass($return) : $return;
        }

        return action($action, ['order_sn' => $order['number'], 'total_amount' => $order['price'], 'returnJson' => $returnJson]);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function info($id) {
        $goodInfo = Db::name('user_address_goods')->where(['id' => $id, 'delete_time' => 0])->field('create_time,update_time,delete_time', 'filter')->find();
        if (!$goodInfo) {
            return $this->miss('商品不存在');
        }
        $store = Db::name('user_claim_address')->where(['id' => $goodInfo['address_id'], 'state' => 1])->field('id,user_id,name,address,longitude,latitude,image_3 image,contact')->cache(60)->find();
        if (!$store) {
            return $this->miss('店铺未找到');
        }
        $goodInfo['store'] = $store;
        if ($store['user_id'] == $this->member['id']) {

        } else {
            if ($goodInfo['state'] != 1 || $goodInfo['status'] != 1) {
                return $this->miss('商品已下架');
            }
            unset($goodInfo['state'], $goodInfo['status'], $goodInfo['reason']);
        }
        return $this->pass($goodInfo);
    }

    /**
     * @param $status
     * @param $page
     * @param $pagesize
     * @param $type
     * @return mixed
     */
    public function orders($status = 0, $page = 1, $pagesize = 20, $type = 0) {
        $rolekey = $type ? 'shopowner' : 'user_id';
        $where   = [$rolekey => $this->member['id']];
        switch ((int) $status) {
        case 1:
            $where['paystate'] = 0;
            break;
        case 2:
            $where['paystate'] = 1;
            $where['status']   = 0;
            break;
        case 3:
            $where['paystate'] = 1;
            $where['status']   = 1;
            $where['comment']  = 0;
            break;
        case 4:
            $where['paystate'] = 1;
            $where['status']   = -1;
            break;
        default:
            break;
        }
        $data = Db::name('order_of_addressgood')
            ->where($where)
            ->field('user_id,shopowner,address_id,delete,data,pay_time,create_time,update_time', 'filter')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->order('create_time desc')
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['expire_time']      = date('Y-m-d H:i:s', $value['expire_time']);
            $data[$key]['show_comment_btn'] = $value['paystate'] == 1 && $value['status'] == 1 && $value['comment'] == 0;
            unset($data[$key]['comment']);
        }
        return $this->pass($data);
    }

    /**
     * @param $order_id
     * @return mixed
     */
    public function OrderDetail($order_id) {
        $data = Db::name('order_of_addressgood')
            ->where(['id' => $order_id])
            ->find();
        if (in_array($this->member['id'], [$data['user_id'], $data['shopowner']])) {
            if ($this->member['id'] == $data['user_id']) {
                if (in_array($data['delete'], [1, 3])) {
                    return $this->miss('订单不存在');
                }
            } else {
                if (in_array($data['delete'], [2, 3])) {
                    return $this->miss('订单不存在');
                }
            }
        } else {
            return $this->miss('订单不存在');
        }
        unset($data['delete']);
        $data['data']             = json_decode($data['data'], true);
        $data['store']            = Db::name('user_claim_address')->where(['id' => $data['address_id'], 'state' => 1])->field('id,user_id,name,address,longitude,latitude,image_3 image,contact')->cache(60)->find();
        $data['expire_time']      = date('Y-m-d H:i:s', $data['expire_time']);
        $data['create_time']      = date('Y-m-d H:i:s', $data['create_time']);
        $data['update_time']      = date('Y-m-d H:i:s', $data['update_time']);
        $data['pay_time']         = date('Y-m-d H:i:s', $data['pay_time']);
        $data['show_comment_btn'] = $data['paystate'] == 1 && $data['status'] == 1 && $data['comment'] == 0;
        return $this->pass($data);
    }

    /**
     * @param $id
     * @param $value
     * @return mixed
     */
    public function setStock($id, $value) {
        if ($value < 0 || $value > 999999999) {
            return $this->miss('操作失败');
        }
        $good = Db::name('user_address_goods')->where(['id' => $id, 'delete_time' => 0])->find();
        if (!$good) {
            return $this->miss('商品不存在');
        }
        $store = Db::name('user_claim_address')->where(['id' => $good['address_id'], 'user_id' => $this->member['id'], 'state' => 1])->cache(60)->find();
        if (!$store) {
            return $this->miss('无权操作');
        }

        $cachekey = 'AddressGoodsetStock' . $id;
        $num      = cache($cachekey);
        if ($num >= 3) {
            return $this->miss('操作频繁');
        }
        $num = $num ? ++$num : 1;
        cache($cachekey, $num, 10);

        $update = ['stock' => $value];
        $result = Db::name('user_address_goods')->where(['id' => $id])->update($update);
        if ($result) {
            return $this->pass('操作成功');
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $order_id
     * @return mixed
     */
    public function writeOff($order_id) {
        $data = Db::name('order_of_addressgood')
            ->where(['id' => $order_id, 'status' => 0, 'paystate' => 1])
            ->find();
        if (!$data) {
            return $this->miss('操作异常');
        }
        if ($this->member['id'] != $data['shopowner']) {
            return $this->miss('订单不存在');
        }
        $result = Db::name('order_of_addressgood')->where(['id' => $order_id])->update(['status' => 1, 'update_time' => time()]);
        if ($result) {
            YaoqingRecords::index($data['shopowner'], $data['user_id'], $data['price'] * 5, '店铺订单核销成功 no.' . $data['number'], 1, '', 0);
            return $this->pass('操作成功');
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $order_id
     * @param $star
     * @param $content
     * @param $images
     * @return mixed
     */
    public function comment($order_id, $star = 3, $content = '', $images = '') {
        $data = Db::name('order_of_addressgood')
            ->where(['id' => $order_id, 'paystate' => 1])
            ->find();
        if (!$data || $this->member['id'] != $data['user_id']) {
            return $this->miss('订单不存在');
        }
        if ($data['status'] != 1) {
            return $this->miss('使用后方才能评价');
        }
        if ($data['comment'] == 1) {
            return $this->miss('订单已评价');
        }
        $timenow = time();
        $comment = [
            'order_id'    => $order_id,
            'user_id'     => $this->member['id'],
            'good_id'     => $data['good_id'],
            'address_id'  => $data['address_id'],
            'content'     => $content,
            'star'        => $star,
            'images'      => $images,
            'create_time' => $timenow,
            'update_time' => $timenow,
        ];
        $rules = [
            'content' => 'require|max:255',
            'images'  => 'require',
            'star'    => 'require|in:1,2,3',
        ];

        $msg = [
            'content.require' => '评论内容必填',
            'content.max'     => '评论内容最多不能超过255个字符',
            'images.require'  => '图片必须上传',
            'star.require'    => '评分选择错误',
            'star.in'         => '评分选择错误',
        ];
        $validate = new Validate($rules, $msg);
        if (!$validate->check($comment)) {
            return $this->miss($validate->getError());
        }
        $res = Db::name('order_of_addressgood_comment')->insert($comment);
        if ($res) {
            Db::name('order_of_addressgood')->where(['id' => $data['id']])->setField('comment', 1);
            return $this->pass('评价成功');
        }
        return $this->miss('评价失败,请重试');
    }

    /**
     * @param $page
     * @param $pagesize
     * @param $address_id
     * @return mixed
     */
    public function comments($page = 1, $pagesize = 20, $address_id) {
        $data = Db::name('order_of_addressgood_comment')
            ->where(['address_id' => $address_id])
            ->field('id,content,images,star,user_id')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['user']   = _user_cache($value['user_id']);
            $data[$key]['images'] = explode(',', $value['images']);
        }
        return $this->pass($data);
    }
}